<template>
  <div class="singlePie">
    <div class="theSinglePie" :id=id style="height: 200px;width:400px;"></div>
    <!-- <base-button text="导出所有" checked @click="handleExportAll('接口名称', params)" /> -->
  </div>
</template>
<script setup>
import * as echarts from 'echarts';
// import { ElMessage } from 'element-plus';
import { onMounted, computed } from 'vue';

const props = defineProps({
  data: Object
})
const id = props.data.id;
const data = props.data.data;
const sum = props.data.sum;
const type = props.data.type;
const theColorList = props.data.theColorList;
const sumOrSingle = props.data.sumOrSingle;
const percentInner = props.data.percentInner;

let dataHandled = computed(() => {
  let dataArr = [];
  for (let j = 0; j <= data.length - 1; j++) {
    let result = [], counter = 0;
    let theData = data[j].value.toString();
    let num = theData;
    for (let i = num.length - 1; i >= 0; i--) {
      counter++;
      result.unshift(num[i]);
      if (!(counter % 3) && i != 0) { result.unshift(','); }
    }
    let theValue = result.join('');
    dataArr.push(theValue);
  }
  return dataArr
})
let theSum = computed(() => {
  let result = [], counter = 0;
  let theData = sum.toString();
  let num = theData;
  for (let i = num.length - 1; i >= 0; i--) {
    counter++;
    result.unshift(num[i]);
    if (!(counter % 3) && i != 0) { result.unshift(','); }
  }
  let theValue = result.join('')
  return theValue
})


onMounted(() => {
  if (sumOrSingle === undefined && percentInner === undefined) {
    getThePie()
  } else {
    getTheSumPie()
  }
})

const getTheSumPie = () => {
  var chartDom = document.getElementById(id);
  var myChart = echarts.init(chartDom);
  var option;
  option = {

    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        zlevel: 2,
        clockwise: false,
        type: 'pie',
        radius: ['55%', '65%'],
        itemStyle: {
          color: (params) => {
            return theColorList[params.dataIndex]
          }
        },
        label: {
          show: true,
          position: 'outer',
          alignTo: 'none',
          color: '#ffffff',
          fontSize: 14,
          lineHeight: 20,
          padding: [0, -90],

          formatter: (params) => {
            return `{font|${params.name}}\n{num|${dataHandled.value[params.dataIndex]} ${params.percent.toFixed(1)}%}`
          },
          rich: {
            font: {
              color: '#ffffffc0',
              fontSize: 14,
              lineHeight: 20,
              fontFamily: "PingFang-Medium",
            },
            num: {
              fontSize: 14,
              lineHeight: 20,
              fontFamily: "PingFang-Bold",
              fontWeight: 'bold'
            }
          }
        },
        labelLayout: {
          verticalAlign: "bottom"
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 120
        },
        emphasis: {
          scale: true,
          scaleSize: 15,
        },
        data: data
      },
      {
        clockwise: false,
        type: 'pie',
        radius: ['55%', '65%'],
        label: {
          show: true,
          fontSize: 14,
          position: 'center',
          color: '#ffffff',
          formatter: (params) => {
            if (sumOrSingle != undefined && percentInner === undefined) {
              return `{font|${sumOrSingle}}\n\n{a|${theSum.value}}`
            } else if (percentInner != undefined && sumOrSingle === undefined) {
              return `{font|${percentInner.text}}\n\n{a|${percentInner.percent}}`
            }
          },
          rich: {
            font: {
              fontFamily: 'PingFang-Medium'
            },
            a: {
              fontSize: 18,
              fontWeight: 600,
              fontFamily: 'PingFang-Bold'
            }
          }
        },
        labelLayout: {
          verticalAlign: "center",
        },
        labelLine: {
          show: false,
        },
        emphasis: {
          disabled: true,
        },
        data: data
      },

    ]
  };
  option && myChart.setOption(option);
}

const getThePie = () => {
  var chartDom = document.getElementById(id);
  var myChart = echarts.init(chartDom);
  var option;
  option = {

    color: theColorList,
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        clockwise: false,
        type: 'pie',
        radius: ['55%', '65%'],
        label: {
          lineHeight: 20,
          show: true,
          position: 'outer',
          fontSize: 14,
          alignTo: 'none',
          padding: [0, -90],
          color: '#ffffff',
          formatter: (params) => {
            return `{font|${params.name}}\n{num|${dataHandled.value[params.dataIndex]} ${params.percent.toFixed(1)}%}`
          },
          rich: {
            font: {
              color: '#ffffffc0',
              fontSize: 14,
              lineHeight: 20,
              fontFamily: "PingFang-Medium",
            },
            num: {
              fontSize: 14,
              lineHeight: 20,
              fontFamily: "PingFang-Bold",
              fontWeight: 'bold'
            }
          }
        },
        labelLayout: {
          verticalAlign: "bottom",
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 100
        },
        emphasis: {
        },
        data: data
      },
      {
        clockwise: false,
        type: 'pie',
        radius: ['55%', '65%'],
        label: {
          show: false,
          position: 'center',
          color: '#ffffff'
        },
        emphasis: {
          scale: true,
          scaleSize: 15,
          label: {
            show: true,
            fontSize: 14,
            color: '#ffffff',
            formatter: (params) => {
              if (type == 'value') {
                return `${params.name}\n\n{a|${dataHandled.value[params.dataIndex]}}`
              } else if (type == 'percent') {
                return `${params.name}率占比\n\n{a|${params.percent}%}`
              }
            },
            rich: {
              a: {
                fontSize: 18,
                fontWeight: 600
              }
            }
          }
        },

        data: data
      },

    ]
  };
  option && myChart.setOption(option);
}

/**
 * 导出到表格
 * @param exportApi {String} Api接口名称
 * @param formData {Object} 查询数据
 * @return void
*/

// const handleExportAll = (exportApi, formData = {}) => {
//   if (total.value === 0) { // 获取总条数
//     ElMessage.warning('无数据,不能执行导出操作')
//   } else {
//     axios.post(`${import.meta.env.VITE_APP_API}${exportApi}`, formData, {
//       responseType: 'blob',
//       headers: {
//         token: getToken()
//       }
//     }).then((res) => {
//       // 获取到请求头中的content-disposition 并用decodeURIComponent进行转换
//       const newName = decodeURIComponent(res.headers['content-disposition']?.split('=')[1]).length > 9 ? decodeURIComponent(res.headers['content-disposition']?.split('=')[1]) : '设备检查列表导出.xlsx'
//       const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
//       const downloadElement = document.createElement('a')
//       const href = window.URL.createObjectURL(blob) // 创建下载的链接
//       downloadElement.href = href
//       downloadElement.download = newName // 下载后文件名
//       document.body.appendChild(downloadElement)
//       downloadElement.click() // 点击下载
//       document.body.removeChild(downloadElement) // 下载完成移除元素
//       window.URL.revokeObjectURL(href) // 释放掉blob对象
//       ElMessage.success('导出成功')
//       // const newName1 = decodeURIComponent(res.headers['content-dispotion']?.split('=')[1]).length > 9 ? decodeURIComponent(res.headers['content-disposition']?.split('=')[1]) : '设备检查列表导出.xlsx'
//       // const blob1 = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
//       // const downloadElement1 = document.createElement('a')
//       // const href1 = window.URL.createObjectURL(blob1)
//       // downloadElement1.href = href1
//       // downloadElement.download = newName1
//       // document.body.appendChild(downloadElement1)
//       // downloadElement1.click()
//       // document.body.removeChild(downloadElement1)
//       // window.URL.revokeObjectURL(href1)
//       // ElMessage.success('导出成功')
//     }).catch((error) => {
//       console.log(error)
//       ElMessage.error('导出失败')
//     })
//   }
// }
/**
 * 导入excel模版
 * @param importApi {String} 导入的api
 * * @param id{String} 导入的参数
 */
// const handleImportExcel = (importApi, id) => {
//   const element = document.getElementById("global-upload");
//   element.click();
//   element.onchange = (e) => {
//     const { files } = e.target;
//     if (files[0]) {
//       const param = new FormData();
//       param.append("file", files[0]);
//       if (id === Number) {
//         param.append("id", id);
//       } else {
//         param.append("exeId", idexeId);
//         param.append("exeName", id.exeName);
//       }
//       axios.post(`${import.meta.env.VITE_URL}${importApi}`, param
//       ).then((response) => {
//         const res = response.data;
//         if (res.code === 0) {
//           ElMessage.success("上传成功");
//         } else {
//           ElMessage.error(res.msg);
//         }
//         element.value = null;
//       }).catch((error) => {
//         ElMessage.error(error);
//       });
//     }
//   }
// } //https://blog.csdn.net/qq_67118860/article/details/129416838#comments_27381562
</script>
<style scoped>
.singlePie {
  display: flex;
  justify-content: center;
  align-items: center;
}

.theSinglePie {
  background-image: url('@/assets/images/wrappedSinglePie.png');
  background-position: center center;
  background-repeat: no-repeat;
}
</style>